<?
    header('Content-type: text/html; charset=utf-8');
    $error = 0;
    $errormessage = '';
    if (isset($_GET['error'])) {
        $error = $_GET['error'];
    }
    if ($error != '0') {
        $error = 1;
        $errormessage = 'test error message';
    }
    $count = 5;
    if (isset($_GET['count'])) {
        $count = $_GET['count'];
    }

    $connection = mysql_connect ('localhost', 'zorik_if039', '9731') or die ('Unable to connect!');
	mysql_select_db('zorik_if039') or die (mysql_error());
	mysql_query("set character_set_client='utf8'"); 
	mysql_query("set character_set_server='utf8'"); 
	mysql_query("set character_set_results='utf8'"); 
	mysql_query("set collation_connection='utf8_unicode_ci'");

    $query = "select added, id, title, filename, description, tags, user_id, longitude, latitude, date, categoryid, AVG(rating) rating from (
    SELECT p . * , IFNULL( r.rating, 0 ) rating
    FROM photo AS p
    LEFT JOIN rating AS r ON ( p.id = r.photoid )
    ) AS pr
    group by added, tags, user_id, longitude, latitude, date, filename, description, title, categoryid, id
    order by rating DESC, added DESC
    limit 0, $count";
	$res = mysql_query($query) or die(mysql_error());
	$rows = array();
	while($r = mysql_fetch_assoc($res)) {
        $rows[] = $r;
    }

    for ($i = 0; $i < $count; $i++) {
        $user_id = $rows[$i]['user_id'];

        $query = "SELECT * FROM user where id='$user_id'";
        $res = mysql_query($query) or die(mysql_error());
        $user = array();
        while($r = mysql_fetch_assoc($res)) {
            $user[] = $r;
        }
        $rows[$i]['user'] = $user[0];
    }

    if ($error == 0) {
        $photoList = (object) array('error' => $error, 'errormessage' => $errormessage, 'data' => $rows);
        //$photoList -> data[0]['user'] = $user[0];
    } else {
        $photoList = (object) array('error' => $error, 'errormessage' => $errormessage, 'data' => '');
    }
    echo json_encode($photoList);
    mysql_close($connection);
?>